package com.lzy.crm.wechat.util;

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.vo.AccessToken;


public class ImgUtil {

	
	Logger logger= Logger.getLogger(ImgUtil.class);
	
	private Integer imgType_url =1;

	/**
	 * 生产带参数的二维码  1 公众号二维码  2 路径图片
	 * @param codeImg
	 * @param type
	 * @return
	 */
	public String createImg(String codeImg,Integer type) {
		try {
			String imgPath = "E://img/3.jpg";
			BufferedImage image = ImageIO.read(new FileInputStream(imgPath));
			BufferedImage image2 = LogoMatrix(image,codeImg ,type);
			File file2 = new File("e:/img/"); // 此目录保存缩小后的关键图
			if (file2.exists()) {
				//System.out.println("多级目录已经存在不需要创建！！");
			} else {
				// 如果要创建的多级目录不存在才需要创建。
				file2.mkdirs();
			}
			String path = "E://img/"+WeixinUtil.getTimeStamp()+ WeixinUtil.getNonceStr()+".jpg" ;
			ImageIO.write(image2, "jpg", new File(path));
			return path;
		} catch (FileNotFoundException e) {
			logger.error("没找到文件", e);
		} catch (IOException  e) {
			logger.error("io 错误", e);
		}
		return null;
	}
	
	/**
	 * 设置 logo
	 * 
	 * @param matrixImage
	 *            源二维码图片
	 * @return 返回带有logo的二维码图片
	 * @throws IOException
	 * @author Administrator sangwenhao
	 */
	public BufferedImage LogoMatrix(BufferedImage matrixImage,String codeImg,Integer type)
			throws IOException {
		/**
		 * 读取二维码图片，并构建绘图对象
		 */
		Graphics2D g2 = matrixImage.createGraphics();

		int matrixWidth = matrixImage.getWidth();
		int matrixHeigh = matrixImage.getHeight();
		//System.out.println(matrixWidth + "" + matrixHeigh);
		
		/**
		 * 读取二维码图片
		 */
		//String code="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGL8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyQWJ5cGRLMl9lbjIxMDAwMGcwNzcAAgRU8jhZAwQAAAAA";
		BufferedImage logo =null;
		if(type==imgType_url){
			URL uloge =new URL(codeImg);
			logo = ImageIO.read(uloge);
		}else{
			logo = ImageIO.read(new File(codeImg));
		}
		
		// 开始绘制图片
		// g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5,
		// matrixHeigh/5, null);//绘制 g2.drawImage(logo, 410, 491, 284, 280, null);// 绘制
		//g2.drawImage(logo, 434, 530, 265, 263, null);// 绘制
		//g2.drawImage(logo, 440, 530, 261, 261, null);// 绘制
		g2.drawImage(logo, 430, 430, 261, 261, null);// 绘制
		System.out.println(matrixWidth / 5 * 2 + "-" + matrixHeigh / 5 * 2
				+ "-" + matrixWidth / 5 + "-" + matrixHeigh / 5);
		BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND,
				BasicStroke.JOIN_ROUND);
		g2.setStroke(stroke);// 设置笔画对象

		/**
		 * 头像图片
		 */
		/*String img100 ="http://wx.qlogo.cn/mmopen/PiajxSqBRaELTPiaq1wZ5BpoD0cej1NuTSXPQHfibEpTcHjQIahzQTibBMoHkIq232xmhmOIJMPQCkNAVqrpYH5GdQ/0";
		//BufferedImage head = ImageIO.read(new File("E:\\100.jpg"));
		//url 转图片
		URL u =new URL(img100);
		BufferedImage head = ImageIO.read(u);
		// 开始绘制图片
		g2.drawImage(head, 482, 290, 120, 120, null);// 绘制
		BufferedImage image = new BufferedImage(50, 30, 1);
		Graphics g = createGraphics(image);

		// 昵称图片
		// 图片中文本行高
		final int Y_LINEHEIGHT = 15;
		int lineNum = 1;
		g.drawString("水晶~", 0, lineNum * Y_LINEHEIGHT);
		g.dispose();
		// 保存为jpg图片
		g2.drawImage(image, 510, 412, 70, 40, null);// 绘制
		g2.dispose();*/
		matrixImage.flush();
		
		return matrixImage;
	}

	/*private Graphics createGraphics(BufferedImage image) {
		Graphics g = image.createGraphics();
		g.setColor(Color.BLACK); // 设置背景色
		g.fillRect(0, 0, 80, 40);// 绘制背景
		g.setColor(Color.WHITE); // 设置前景色
		g.setFont(new Font("微软雅黑", Font.PLAIN, 22)); // 设置字体
		return g;
	}*/

	
	
	// 上传图片到微信
	public  String postFile( String filePath,String access_token) {
		String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=image".replace("ACCESS_TOKEN", access_token);
		File file = new File(filePath);
		if (!file.exists())
			return null;
		String result = null;
		try {
			
			URL url1 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Cache-Control", "no-cache");
			String boundary = "-----------------------------" + System.currentTimeMillis();
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

			OutputStream output = conn.getOutputStream();
			output.write(("--" + boundary + "\r\n").getBytes());
			output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
							.getBytes());
			output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
			byte[] data = new byte[1024];
			int len = 0;
			
			
			
			FileInputStream input = new FileInputStream(file);
			while ((len = input.read(data)) > -1) {
				output.write(data, 0, len);
			}
			output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
			output.flush();
			output.close();
			input.close();
			
			
			InputStream resp = conn.getInputStream();
			StringBuffer sb = new StringBuffer();
			while ((len = resp.read(data)) > -1)
				sb.append(new String(data, 0, len, "utf-8"));
			resp.close();
			result = sb.toString();
			
		} catch (ClientProtocolException e) {
			
			logger.error("postFile，不支持http协议");
		} catch (IOException e) {
			logger.error("postFile数据传输失败");
		}
		System.out.println(result);
		return result;
	}

	
	
	
	/**********  生产带参数的二维码链接   **************/
	
	
	
	/* public static void main(String[] args) {
        String url = "http://baidu.com";
        String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
        createQrCode(url, path, fileName);
    }*/
 
    public  String createQrCode(String url) {
        String fileName ="";
        String path = "E://img/";
    	try {
            fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
        	
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
            File file = new File(path, fileName);
            if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
                writeToFile(bitMatrix, "jpg", file);
                System.out.println("搞定：" + file);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path+fileName;
    }
 
    static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
 
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
    /**********  生产带参数的二维码链接   **************/
	
	
	public  String postFile1( String filePath) {
		AccessToken accessToken = WeixinUtil.getAccessToken(WechatPayProperties.getAppId() , WechatPayProperties.getAppSecret());
		String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=image".replace("ACCESS_TOKEN", accessToken.getToken());
		File file = new File(filePath);
		if (!file.exists())
			return null;
		String result = null;
		try {
			URL url1 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Cache-Control", "no-cache");
			String boundary = "-----------------------------" + System.currentTimeMillis();
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

			OutputStream output = conn.getOutputStream();
			output.write(("--" + boundary + "\r\n").getBytes());
			output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
							.getBytes());
			output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
			byte[] data = new byte[1024];
			int len = 0;
			
			
			
			FileInputStream input = new FileInputStream(file);
			while ((len = input.read(data)) > -1) {
				output.write(data, 0, len);
			}
			output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
			output.flush();
			output.close();
			input.close();
			
			
			InputStream resp = conn.getInputStream();
			StringBuffer sb = new StringBuffer();
			while ((len = resp.read(data)) > -1)
				sb.append(new String(data, 0, len, "utf-8"));
			resp.close();
			result = sb.toString();
			
			
			System.out.println(result);
		} catch (ClientProtocolException e) {
			
			logger.error("postFile，不支持http协议");
		} catch (IOException e) {
			logger.error("postFile数据传输失败");
		}
		System.out.println(result);
		return result;
	}
	
	
	//

	
	
	
	public static void main(String[] args) throws FileNotFoundException,
			IOException {

		ImgUtil imgUtil = new ImgUtil();
		String imgPath = "e://1.jpg";
		String code="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGL8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyQWJ5cGRLMl9lbjIxMDAwMGcwNzcAAgRU8jhZAwQAAAAA";

		BufferedImage image = ImageIO.read(new FileInputStream(imgPath));
		BufferedImage image2 = imgUtil.LogoMatrix(image,code,1);
		File file2 = new File("e:/"); // 此目录保存缩小后的关键图
		if (file2.exists()) {
			System.out.println("多级目录已经存在不需要创建！！");
		} else {
			// 如果要创建的多级目录不存在才需要创建。
			file2.mkdirs();
		}
		ImageIO.write(image2, "jpg", new File("e://code1.jpg"));

	}
	

}
